const express=require("express");
const handleDB=require("../db/handleDB");
const common=require("../utils/common");
const constant=require("../utils/constant");
const md5=require("md5");
const Captcha=require("../utils/captcha");
const keys = require("../utils/keys");
const jwt=require("jsonwebtoken");
require("../utils/filter");
const multer=require("multer");

const storage=multer.diskStorage({
    destination:function(req,file,cb){
        cb(null,'public/upload/avatar')
    },
    filename:function(req,file,cb){
        cb(null,file.originalname)
    }
})
const upload=multer({storage:storage})

const router=express.Router();

router.get("/web_user/",(req,res)=>{
    (async function(){
        let userInfo=await common.getUserInfo(req,res);

        let number="";
        if(userInfo[0]){
            let indentCounts=await handleDB(res,"indent","sql","数据库查询出错",`select count(*) from indent where user_id=${userInfo[0].user_id} and is_order=0`);
            number=indentCounts[0]["count(*)"];
        }
        let data={
            user_info:userInfo[0]?{
                nick_name:userInfo[0].nick_name,
                head_url:userInfo[0].head_url?userInfo[0].head_url:"/images/worm.jpg",
                abstract:userInfo[0].abstract
            }:false,
            number:number
        };
        res.render("./web_user",data);
    })();
})

router.all("/web_user_basic_info/",(req,res)=>{
    (async function(){
        let userInfo=await common.getUserInfo(req,res);
        if(req.method==="GET"){
            let data={
                nick_name:userInfo[0].nick_name,
                mail:userInfo[0].mail,
                abstract2:userInfo[0].abstract
            }
            res.render("./web_user_basic_info",data)
        }else if(req.method==="POST"){
            let {nick_name,mail,abstract2}=req.body
            if(!nick_name || !mail || !abstract2){
                res.send({errmsg:"参数错误"})
                return
            }

            await handleDB(res,"user","update","数据库更新数据出错",`user_id=${userInfo[0].user_id}`,{
                nick_name,
                mail,
                abstract:abstract2
            })

            res.send({errno:"0",errmsg:"操作成功"})
        }
    })();
})

router.all("/web_user_password/",(req,res)=>{
    (async function(){
        let userInfo=await common.getUserInfo(req,res);

        if(req.method==="GET"){
            res.render("./web_user_password")
        }else if(req.method==="POST"){
            let {old_password,new_password,new_password2}=req.body
            if(!old_password || !new_password || !new_password2){
                res.send({errmsg:"参数错误"})
                return
            }

            if(new_password!==new_password2){
                res.send({errmsg:"两次密码不一致"})
                return
            }

            if(md5(md5(old_password)+keys.password_salt)!==userInfo[0].password){
                res.send({errmsg:"旧密码不正确，修改失败"})
                return
            }

            await handleDB(res,"user","update","数据库更新数据出错",`user_id=${userInfo[0].user_id}`,{
                password:md5(md5(new_password)+keys.password_salt)
            })

            res.send({errno:"0",errmsg:"操作成功"})
        }
    })();
})
router.get("/web_user_receiving_address/",(req,res)=>{
    (async function(){
        let userInfo=await common.getUserInfo(req,res);
        let result=await handleDB(res,"receiving_address","find","数据库查询出错",`user_id=${userInfo[0].user_id}`)
        let data={
            result:result
        }

        res.render("./web_user_receiving_address",data);
    })();
})
router.post("/web_user_receiving_address/",(req,res)=>{
    (async function(){
        let userInfo=await common.getUserInfo(req,res);
        let {address,user_name,phone}=req.body
        if(!address || !user_name || !phone){
            res.send({errmsg:"参数错误"})
            return
        }
        let result2=await handleDB(res,"receiving_address","insert","数据库插入数据出错",{
            user_id:userInfo[0].user_id,
            user_name:user_name,
            phone:phone,
            address:address
        })
        let data={
            user_name:user_name,
            phone:phone,
            address:address
        }

        res.send({errno:"0",errmsg:"操作成功",data})
    })();
})
router.post("/web_user_receiving_address/del",(req,res)=>{
    (async function(){
        let userInfo=await common.getUserInfo(req,res);

        let {user_id,address_id}=req.body;
        if(!user_id || !address_id){
            res.send({errmsg:"参数错误1"})
            return
        }
        await handleDB(res,"receiving_address","delete","数据库删除失败",`address_id=${address_id} and user_id=${user_id}`)
        res.send({errno:"0",errmsg:"操作成功"});
    })();
})
router.get("/web_user_collect/",(req,res)=>{
    (async function(){
        let userInfo=await common.getUserInfo(req,res);
        let collectResult=await handleDB(res,"collect","find","数据库查询出错",`user_id=${userInfo[0].user_id}`)
        let results=[];
        if(collectResult==undefined){
            results=0;
        }
        else{
            for(var i=0;i<collectResult.length;i++){
                let commodityResult=await handleDB(res,"commodity","find","数据库查询出错",`commodity_id=${collectResult[i].commodity_id}`)
                let merchantResult=await handleDB(res,"user","find","数据库查询出错",`user_id=${commodityResult[0].merchant_id} and is_merchant=1`)
    
                results[i]={
                    collectInfo:{
                        commodity_id:commodityResult[0].commodity_id,
                        commodity_url:commodityResult[0].commodity_url,
                        commodity_name:commodityResult[0].commodity_name,
                        collect_time:collectResult[i].collect_time,
                        nick_name:merchantResult[0].nick_name,
                        head_url:merchantResult[0].head_url
                    }
                }
            }
        }
        let data={
            results
        }

        res.render("./web_user_collect",data);
    })();
})
router.get("/web_user_concern/",(req,res)=>{
    (async function(){
        let userInfo=await common.getUserInfo(req,res);
        //用户关注什么店家
        let concernResult=await handleDB(res,"concern","find","数据库查询出错",`user_id=${userInfo[0].user_id}`)
        for(var i=0;i<concernResult.length;i++){
            //店家关注数量
            let concernCounts=await handleDB(res,"concern","sql","数据库查询出错",`select count(*) from concern where merchant_id=${concernResult[i].merchant_id}`)
            //店家头像,店家名称
            let merchantResult=await handleDB(res,"user","find","数据库查询出错",`user_id=${concernResult[i].merchant_id}`)
            concernResult[i].commenter={
                merchant_img:merchantResult[0].head_url,
                merchant_name:merchantResult[0].nick_name,
                concern_num:concernCounts[0]["count(*)"]
            }
        }
        if(concernResult[0]==undefined){
            concernResult=0;
        }
        let data={
            concernResult
        }
        res.render("./web_user_concern",data);
    })();
})
router.get("/web_user_merchant/",(req,res)=>{
    (async function(){
        let userInfo=await common.getUserInfo(req,res);
        let is_merchant=await handleDB(res,"user","find","数据库查询出错",`user_id=${userInfo[0].user_id} and is_merchant=1`)
        if(is_merchant[0]==undefined){
            is_merchant=0;
        }
        let data={
            is_merchant
        }
        res.render("./web_user_merchant",data);
    })();
})
router.post("/web_user_merchant/",(req,res)=>{
    (async function(){
        let userInfo=await common.getUserInfo(req,res);
        await handleDB(res,"user","update","数据库更新数据出错",`user_id=${userInfo[0].user_id}`,{
            is_merchant:1
        })
        res.send({errno:"0",errmsg:"操作成功"});
    })();
})
router.get("/web_user_money/",(req,res)=>{
    (async function(){
        let userInfo=await common.getUserInfo(req,res);
        let data={
            money:userInfo[0].money
        }
        res.render("./web_user_money",data);
    })();
})
router.post("/web_user_money/",(req,res)=>{
    (async function(){
        let userInfo=await common.getUserInfo(req,res);
        let {money_add}=req.body
        if(!money_add){
            res.send({errmsg:"参数错误"})
            return
        }
        let number=Number(userInfo[0].money)+Number(money_add);
        console.log(number)
        await handleDB(res,"user","update","数据库插入数据出错",`user_id=${userInfo[0].user_id}`,{
            money:number
        })

        res.send({errno:"0",errmsg:"操作成功"})
    })();
})
router.get("/web_user_commodity_indent/",(req,res)=>{
    (async function(){
        let userInfo=await common.getUserInfo(req,res);
        let indent=await handleDB(res,"indent","find","数据库查询出错",`user_id=${userInfo[0].user_id} and is_order=1`)

        if(indent[0]==undefined){
            indent=0;
        }
        for(var i=0;i<indent.length;i++){
            let commodity=await handleDB(res,"commodity","find","数据库查询出错",`commodity_id=${indent[i].commodity_id}`)
            let address=await handleDB(res,"receiving_address","find","数据库查询出错",`address_id=${indent[i].address_id}`)
            indent[i].nick_name=userInfo[0].nick_name
            indent[i].commodity_name=commodity[0].commodity_name
            indent[i].phone=address[0].phone
            indent[i].address=address[0].address
        }
        let data={
            indent
        }
        res.render("./web_user_commodity_indent",data);
    })();
})

router.get("/user_index_private_letter/",(req,res)=>{
    (async function(){
        //用户的登录记录
        let userInfo=await common.getUserInfo(req,res);

        let result=await handleDB(res,"private_letter","sql","数据库查询出错",`select distinct speak_id,receive_id from private_letter where receive_id=${userInfo[0].user_id}`);
        for(var i=0;i<result.length;i++){
            let speak_id=await handleDB(res,"user","find","数据库查询出错",`user_id=${result[i].speak_id}`)
            let num=await handleDB(res,"private_letter","sql","数据库查询出错",`select count(*) from private_letter where (speak_id=${result[i].speak_id} and receive_id=${userInfo[0].user_id}) or (speak_id=${userInfo[0].user_id} and receive_id=${result[i].speak_id})`);

            result[i].num=num[0]["count(*)"];
            result[i].name=speak_id[0].nick_name;
            result[i].head_url=speak_id[0].head_url?speak_id[0].head_url:"/images/worm.jpg"
        }
        let data={
            result
        }
        res.render("./user_index_private_letter",data);
    })();
})
router.get("/user_index_private_letter/chat/:speak_id",(req,res)=>{
    (async function(){
        //用户的登录记录
        let userInfo=await common.getUserInfo(req,res);
        let {speak_id}=req.params
        console.log(speak_id)
        let speak=await handleDB(res,"user","find","数据库查询出错",`user_id=${speak_id}`)
        speak[0].head_url=speak[0].head_url?speak[0].head_url:"/images/worm.jpg"
        if(!speak[0]){
            common.abort404(req,res);
            return
        }

        let private_letter=await handleDB(res,"private_letter","find","数据库查询出错",`(speak_id=${userInfo[0].user_id} and receive_id=${speak_id}) or (speak_id=${speak_id} and receive_id=${userInfo[0].user_id})`)
        if(private_letter[0]==undefined){
            private_letter=0
        }
        for(var i=0;i<private_letter.length;i++){
            if(private_letter[i].speak_id==userInfo[0].user_id){
                private_letter[i].is=1;
            }
            else{
                private_letter[i].is=0;
            }
        }
        let data={
            user_info:userInfo[0]?{
                user_id:userInfo[0].user_id,
                nick_name:userInfo[0].nick_name,
                head_url:userInfo[0].head_url?userInfo[0].head_url:"/images/worm.jpg"
            }:false,
            speak,
            private_letter
        };
        res.render("./user_index_private_letter_chat",data);
    })();
})

router.get("/web_user_private_letter/",(req,res)=>{
    (async function(){
        //用户的登录记录
        let userInfo=await common.getUserInfo(req,res);

        let result=await handleDB(res,"private_letter","sql","数据库查询出错",`select distinct speak_id,receive_id from private_letter where speak_id=${userInfo[0].user_id}`);
        let result2=[]
        for(var i=0;i<result.length;i++){
            let receive=await handleDB(res,"user","find","数据库查询出错",`user_id=${result[i].receive_id}`)
            let num=await handleDB(res,"private_letter","sql","数据库查询出错",`select count(*) from private_letter where (speak_id=${userInfo[0].user_id} and receive_id=${result[i].receive_id}) or (speak_id=${receive[0].user_id} and receive_id=${userInfo[0].user_id})`);

            result[i].num=num[0]["count(*)"];
            result[i].nick_name=receive[0].nick_name
            result[i].head_url=receive[0].head_url
            if(receive[0].is_merchant==1){
                result2.push(result[i])
            }
        }
        let data={
            result2
        }
        res.render("./web_user_private_letter",data);
    })();
})
router.get("/web_user_private_letter/chat/:receive_id",(req,res)=>{
    (async function(){
        //用户的登录记录
        let userInfo=await common.getUserInfo(req,res);
        let {receive_id}=req.params
        console.log(receive_id)
        let receive=await handleDB(res,"user","find","数据库查询出错",`user_id=${receive_id}`)
        if(!receive[0]){
            common.abort404(req,res);
            return
        }

        let private_letter=await handleDB(res,"private_letter","find","数据库查询出错",`(speak_id=${userInfo[0].user_id} and receive_id=${receive_id}) or (speak_id=${receive_id} and receive_id=${userInfo[0].user_id})`)
        if(private_letter[0]==undefined){
            private_letter=0
        }
        for(var i=0;i<private_letter.length;i++){
            if(private_letter[i].speak_id==userInfo[0].user_id){
                private_letter[i].is=1;
            }
            else{
                private_letter[i].is=0;
            }
        }
        let data={
            user_info:userInfo[0]?{
                user_id:userInfo[0].user_id,
                nick_name:userInfo[0].nick_name,
                head_url:userInfo[0].head_url?userInfo[0].head_url:"/images/worm.jpg"
            }:false,
            receive,
            private_letter
        };
        res.render("./web_user_private_letter_chat",data);
    })();
})

router.post("/web_user_private_letter/chat/add",(req,res)=>{
    (async function(){
        //用户的登录记录
        let userInfo=await common.getUserInfo(req,res);
        let {receive_id,content}=req.body
        if(!receive_id ||!content){
            res.send({errmsg:"参数错误1"})
            return
        }
        await handleDB(res,"private_letter","insert","数据库添加出错",{
            speak_id:userInfo[0].user_id,
            receive_id:receive_id,
            content
        })
        res.send({errno:"0",errmsg:"成功！"})
    })();
})
module.exports=router